#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>

#define MAXNUM 1024

int clientFd[1024];
int serverFd;
void hand(int s)
{
    if (2==s)
    {
        //close 断开链接
        printf("bye bye\n");
        for (int i=0;i<MAXNUM;i++)
        {
            if (clientFd[i]!=-1)
            {
                close(clientFd[i]);
            }
        }

        close(serverFd);
        exit(1);
    }
}

void init()
{
    for (int i=0;i<MAXNUM;i++)
    {
        clientFd[i]=-1;
    }
}

void *handle_client(void *arg)
{
    char buff[1024];
    char temp[1024];
    int n=0;
    int* clientFd  =(int*) arg;
    while (1)
    {
        int r = recv(*clientFd,buff,1023,0);
        if (r>0)
        {
            buff[r] = 0; //添加字符串结束符号
            printf("%d:%s\n",r,buff);
            sprintf(temp,"%d-%s",n++,buff);
            send(*clientFd,temp,strlen(temp),0);
        }
    }
}


int main(){

    init();
    signal(2,hand);

    //创建socket
    serverFd = socket(AF_INET,SOCK_STREAM,0);
    if (-1==serverFd)
    {
        printf("创建socket失败\n");
        exit(-1);
    }
    printf("创建socket成功\n");

    //协议地址簇
    struct sockaddr_in addr={0};
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr=inet_addr("127.0.0.1");//ip地址 注意字符串转网络字节序
    addr.sin_port=htons(4556);


    //绑定
    int r = bind(serverFd,( struct sockaddr*)&addr,sizeof addr);

    if (-1==r)
    {
        printf("绑定失败:%m\n");
        close(serverFd);
        exit(-1);
    }
    printf("绑定成功\n");

    //监听
    r = listen(serverFd,100);
    if (-1==r)
    {
        printf("监听失败:%m\n");
        close(serverFd);
        exit(-1);
    }
    printf("监听成功\n");

    //接受客户端连接

    struct sockaddr_in cAddr = {0}; //用来接受客户端的协议地址簇
    int len = sizeof cAddr;
    int nn=0;
    pthread_t threads[MAXNUM];
    while (nn<MAXNUM)
    {
        clientFd[nn] = accept(serverFd,(struct sockaddr*)&cAddr,&len);
        if (-1==clientFd[nn])
        {
            printf("服务器崩溃:%m\n");
            close(serverFd);
            exit(-1);
        }
        printf("接受客户端成功：%d %s %u\n",clientFd[nn],inet_ntoa(cAddr.sin_addr),cAddr.sin_port);

        if (pthread_create(&threads[nn], NULL, handle_client, &clientFd[nn]))
        {
            fprintf(stderr, "Error creating thread\n");
            return 1;
        }
        //通信
        nn++;
    }
    for (int i = 0; i < nn; i++) {
        pthread_join(threads[i], NULL);
    }
    printf("Main: All threads completed.\n");
}
